import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'dva';
import { Tree } from 'antd';
import _ from 'lodash';

import AutoHeightScroller from '@/components/containers/autoHeightScroller';

import styles from './index.less';
import layerUtils from '@/utils/arcgis/view/index';

const TreeNode = Tree.TreeNode;

/**
 * 平展开选中节点下挂的所有图层
 * @param node
 */
function toLayerListNodes(node) {
  if (node.url) {
    return [node];
  }

  const ret = [];

  if (node.child) {
    _.each(node.child, c => ret.push(...toLayerListNodes(c)));
  }

  if (node.modelList) {
    _.each(node.modelList, m => ret.push(...toLayerListNodes(m)));
  }

  return ret;
}

const LayerListCustom = ({ dispatch, bimmodel, layerlist }) => {

  const [dataSrc, setData] = useState([]);

  useEffect(() => {
    if(bimmodel.bimTree){
      setData(bimmodel.bimTree);
    }
  }, [bimmodel.bimTree]);

  function loopFind(parent, id) {
    let ret;

    for (let i = 0; i < parent.length; i += 1) {
      if (`${parent[i].objectid}` === id) {
        ret = parent[i];
      } else if (parent[i].child && parent[i].child.length > 0) {
        ret = loopFind(parent[i].child, id);
      } else if (parent[i].modelList && parent[i].modelList.length > 0) {
        ret = loopFind(parent[i].modelList, id);
      }

      if (ret) break;
    }

    return ret;
  }

  function renderNodes(parent) {

    const nodes = [];
    _.each(parent, (p, index) => {
      const key = `${p.name}-${p.objectid}`;
      // 查看key值
      // console.log(key);
      if(p.name.indexOf(layerlist.searchBimMap) > -1){
        nodes.push(
          <TreeNode title={`${p.name}${p.version || ''}`} key={`${p.name}-${p.objectid}`}>
            {renderNodes(p.child || p.modelList)}
          </TreeNode>,
        )
      } else{
        nodes.push('')
      }
     
    });
    return nodes;
  }

  return (
    <div className={styles.treewrap}>
      <AutoHeightScroller>
      {bimmodel.bimTree ? <Tree
          checkable
          className={styles.tree}
          onExpand={(checkedKeys, e) => {
            dispatch({ type: 'layerlist/setTreenodeArr', payload: checkedKeys });
          }}
          checkedKeys={layerlist.checkedKeys}
          onCheck={(checkedKeys, e) => {
            const key = e.node.props.eventKey;
            const keys = key.split('-');
            if (keys.length > 1) {
              const objectId = keys[keys.length - 1];
              console.log(objectId)
              const raw = loopFind(bimmodel.bimTree, objectId);
              const ll = toLayerListNodes(raw);
              dispatch({ type: 'layerlist/updateCheckedKeys', payload: checkedKeys });
              if (e.checked) {
                ll.map((l)=>{
                  layerlist.arrBimids.push({name:l.name, bimId:l.bimId})
                })
                dispatch({ type: 'layerlist/addLayer', payload: ll });
                dispatch({ type: 'layerlist/setArrBimids', payload: layerlist.arrBimids });
                dispatch({ type: 'layerlist/setNowClickBim', payload: raw });
              } else {
                let splicearr = []
                ll.map((l)=>{
                  splicearr.push({name:l.name, bimId:l.bimId})
                })
                let arr = _.difference(layerlist.arrBimids, splicearr);
                dispatch({ type: 'layerlist/removeLayer', payload: ll });
                dispatch({ type: 'layerlist/setArrBimids', payload: arr });
              }
            }
          }}
          onSelect={(selectedKeys, e) => {
            const title = e.node.props.title;
            const layer = layerUtils.getLayerByTitle(window.agsGlobal.view, title);
            if (layer) {
              layerUtils.zoomTolayer(window.agsGlobal.view, layer);
            }
          }}
          expandedKeys={layerlist.treenodeArr}
        >
          {renderNodes(dataSrc)}
        </Tree>:''}
      </AutoHeightScroller>
    </div>
  );
};

export default connect(({ bimmodel, layerlist }) => {
  return {
    bimmodel,
    layerlist,
  };
})(LayerListCustom);
